package com.ciwong.epaper.modules.wordlist.ui;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.wordlist.WordListReadActivity;
import com.ciwong.epaper.modules.wordlist.adapter.WorkBookAdapter;
import com.ciwong.epaper.modules.wordlist.bean.PageListBean;
import com.ciwong.epaper.modules.wordlist.bean.WorkBookBean;
import com.ciwong.epaper.modules.wordlist.dao.WorkBookDao;
import com.ciwong.epaper.modules.wordlist.util.SpaceItemDecoration;
import com.ciwong.epaper.modules.wordlist.util.WorkBookJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ViewUtil;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * @date :2018/4/12
 * @author: loco
 * @description: 练习册主页面
 * @version:2.4
 */


public class WorkBookActivity extends BaseActivity implements View.OnClickListener, PullToRefreshView.OnHeaderRefreshListener,
        PullToRefreshView.OnFooterRefreshListener {

    //没有数据时的展示
    private LinearLayout llNoData;
    //没有网络时的展示
    private LinearLayout llNoNet;
    //没有网络时的重试按钮
    private Button tv_retry;
    //有数据时的展示
    private LinearLayout llHaveData;
    //有数据时的展示选中了多少个的文字
    private TextView tvCheckedNum;

    //有数据时的提示用户单词来源
    private TextView tvPips;
    //有数据时的展示选中哪个范围的单词
    private TextView tvCheckRange;
    //有数据时的展示 “去练习”还是“开始练习”
    private Button tvPractice;
    //有数据时的展示 “去练习”还是“开始练习”
    private RecyclerView rvWord;
    private PullToRefreshView refreshWorkbook;
    private String textTittle = "刷单词";
    private int COLUMNS = 2;
    private int SPACE_ITEM = 5;
    private WorkBookAdapter workBookAdapter;
    private CheckDialogFragment checkDialogFragment;
    private int THRESHOLD_SELECT = 6;//默认选择单词阈值,现在设置为默认全选中已加载的
    private boolean isHeadRefresh;
    private int default_page = 1;//默认加载页面
    private int curPage = default_page;//当前加载页面
    private int pageSize = 20;//每页默认加载条目数
    private String scoreRange = "0,100";//被查询单词范围（默认 全部）
    private LinkedList<PageListBean> checkedWordList = new LinkedList<>();//选择单词集合
    private int pageCount = 1;
    private int Count = 0;
    private ArrayList<PageListBean> pageList;
    private int maxChecked = 50;//最大选择单词阈值
    private int LOCATIONPOSITION = 0;
    private GridLayoutManager gridLayoutManager;
    private double lastTime = -1;

    @Override
    protected int setView() {
        return R.layout.activity_workbook;
    }

    @Override
    protected void findViews() {

        llNoData = findViewById(R.id.ll_no_data);
        llNoNet = findViewById(R.id.ll_no_net);
        tv_retry = findViewById(R.id.btn_retry);
        llHaveData = findViewById(R.id.ll_have_data);
        tvCheckedNum = findViewById(R.id.tv_checked_num);
        tvPips = findViewById(R.id.tv_tips);
        tvCheckRange = findViewById(R.id.tv_check_range);
        tvPractice = findViewById(R.id.tv_practice);
        rvWord = findViewById(R.id.rv_word);
        refreshWorkbook = findViewById(R.id.refresh_workbook);
    }

    /**
     * 网络加载数据时默认什么都不展示
     */
    private void changeShowIsFirstLoading() {
        llNoData.setVisibility(View.GONE);
        llHaveData.setVisibility(View.GONE);
    }

    /**
     * 根据页面是否有数据展示
     */
    private void changeShowIsHaveData(boolean haveDate) {
        if (haveDate) {
            llNoData.setVisibility(View.GONE);
            llHaveData.setVisibility(View.VISIBLE);
        } else {
            llNoData.setVisibility(View.VISIBLE);
            llHaveData.setVisibility(View.GONE);
        }
    }

    /**
     * 根据页面是否有网络展示
     */
    private void changeShowIsHaveNet(boolean hasNet) {
        if (hasNet) {
            llNoNet.setVisibility(View.GONE);
            llNoData.setVisibility(View.VISIBLE);
            llHaveData.setVisibility(View.VISIBLE);
        } else {
            llNoNet.setVisibility(View.VISIBLE);
            llNoData.setVisibility(View.GONE);
            llHaveData.setVisibility(View.GONE);
        }
    }

    /**
     * 给文字中的数字着色
     *
     * @param tvCheckedNum
     * @param CHECKED_NUM
     */

    private void setPartTextColor(TextView tvCheckedNum, int CHECKED_NUM) {
        tvCheckedNum.setText("已选择" + CHECKED_NUM + "个单词");
        SpannableStringBuilder spannable = new SpannableStringBuilder(tvCheckedNum.getText().toString());
        ForegroundColorSpan redSpan = new ForegroundColorSpan(getResources().getColor(R.color.color_light_green));
        if (CHECKED_NUM < 10)
            spannable.setSpan(redSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        else if (CHECKED_NUM < 100)
            spannable.setSpan(redSpan, 3, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        else if (CHECKED_NUM < 1000)
            spannable.setSpan(redSpan, 3, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        else
            spannable.setSpan(redSpan, 3, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvCheckedNum.setText(spannable);
    }

    @Override
    protected void initEvent() {
        tvCheckRange.setOnClickListener(this);
        tvPractice.setOnClickListener(this);

        refreshWorkbook.setOnHeaderRefreshListener(this);
        refreshWorkbook.setOnFooterRefreshListener(this);

        workBookAdapter = new WorkBookAdapter(this);
        gridLayoutManager = new GridLayoutManager(this, COLUMNS);
        gridLayoutManager.setSmoothScrollbarEnabled(true);
        rvWord.setLayoutManager(gridLayoutManager);
        rvWord.addItemDecoration(new SpaceItemDecoration(ViewUtil.dip2px(this, SPACE_ITEM)));
        rvWord.setAdapter(workBookAdapter);
        workBookAdapter.setOnClickListener(new WorkBookAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(WorkBookAdapter.WorkBookHolder holder, PageListBean workBookItemBean, int position) {
                WorkBookJumpManager.jumpToWordDetailActivity(R.string.go_back, WorkBookActivity.this, workBookAdapter.getData(), position, scoreRange, curPage > 1 ? curPage - 1 : curPage);
            }

            @Override
            public void onItemCheck(WorkBookAdapter.WorkBookHolder holder, PageListBean pageItemBean, int position) {


                if (pageItemBean.getSelected()) {
                    checkedWordList.remove(pageItemBean);
                } else {
                    if (checkedWordList.size() >= maxChecked) {//当选中数量大于最大阈值就不能再选择
                        ToastUtil.INSTANCE.toastInCenter(WorkBookActivity.this, getResources().getString(R.string.word_check_num_limit_toast), Toast.LENGTH_SHORT);
                        return;
                    }
                    checkedWordList.add(pageItemBean);
                }
                pageItemBean.setSelected(!pageItemBean.getSelected());
                workBookAdapter.notifyItemChanged(position, "checkview");
                setPartTextColor(tvCheckedNum, checkedWordList.size());
                if (checkedWordList.size() <= 0 && workBookAdapter.getCheckWordIconVisiable()) {
                    tvPractice.setBackgroundResource(R.color.color_AAB2AE);
                } else {
                    tvPractice.setBackgroundResource(R.color.color_light_green);
                }
            }
        });

        tv_retry.setOnClickListener(new View.OnClickListener() {//重试按钮（网络问题）
            @Override
            public void onClick(View v) {
                if (NetworkUtils.isOnline()) {
                    changeShowIsHaveNet(true);
                    //重新请求服务状态 与本地比对  不来自购买
                    curPage = default_page;
                    getNetWorkBookListByID(scoreRange, curPage, true, false);
                } else {
                    changeShowIsHaveNet(false);
                    ToastUtil.INSTANCE.toastInCenter(WorkBookActivity.this, getResources().getString(R.string.connect_disable5), Toast.LENGTH_LONG);
                }

            }
        });
    }

    @Override
    protected void init() {
        setTitleText(textTittle);
    }

    @Override
    protected void loadData() {
        //由于每次进入或者返回都需要加载所以 把加载逻辑放到 onrestart（）一份
        getNetWorkBookListByID(scoreRange, curPage, true, true);
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        cancle();//使“开始练习” 状态回到“练习”状态
        //其他页面回来，刷新
        curPage = default_page;
        getNetWorkBookListByID(scoreRange, curPage, true, false);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_check_range) {//展示单词范围
            checkWorldRange();
        } else if (i == R.id.tv_practice) {//去练习和开始练习切换
            if (tvPractice.getText().equals("去练习")) {
                checkWord();
            } else {
                startPractice();
            }
        }
    }


    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        refreshNetData(false);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        refreshNetData(true);

    }

    private void refreshComplete(boolean isHeadRefresh) {
        if (isHeadRefresh) {
            refreshWorkbook.onHeaderRefreshComplete();
        } else {
            refreshWorkbook.onFooterRefreshComplete();
        }
    }

    /**
     * 刷新网络数据(true为刷新，false为添加更多)
     *
     * @param boo
     */
    private void refreshNetData(boolean boo) {
        isHeadRefresh = boo;
        if (isHeadRefresh) {
            curPage = default_page;
        }
        getNetWorkBookListByID(scoreRange, curPage, false, false);
    }

    /**
     * 获取网络数据
     *
     * @param scoreRange        选择范围
     * @param curPageForNet     第几页数据
     * @param isFreshOrLoadmore 是否是第一次加载（用于区别于上拉刷新，下拉加载的标记），true表示非上拉和下拉
     * @param isFirstLoad       是否是第一次进入此页面
     */
    private void getNetWorkBookListByID(String scoreRange, int curPageForNet, final boolean isFreshOrLoadmore, boolean isFirstLoad) {
        if (!NetworkUtils.isOnline()) {
            refreshComplete(isHeadRefresh);
            //当时第一次进入此页面，切换有无网络状态。
            changeShowIsHaveNet(false);
            if (isFirstLoad) {
                return;//第一次进入不弹提示
            }
            ToastUtil.INSTANCE.toastInCenter(getBaseApplication(), getResources().getString(R.string.connect_disable5), Toast.LENGTH_LONG);
            return;
        }
        changeShowIsHaveNet(true);
        changeShowIsHaveData(true);//请求成功前白板数据
        if (isFirstLoad) changeShowIsFirstLoading();
        showCricleProgress(null);
        final long start = System.nanoTime();
        WorkBookDao.getInstance().getWorkBookListFromNet(EApplication.BRAND_ID, getUserInfoBase().getUserId(), curPageForNet, pageSize, scoreRange,
                new BaseExtCallBack(this) {
                    @Override
                    public void failed(Object data) {
                        long end = System.nanoTime();
//                        CWLog.d(TAG,"失败 时间end1： " + ((end - start) / (1000000)));
                        super.failed(data);
                        CWLog.d(TAG, "请求失败 curPage" + curPage + "：" + data);
                        refreshComplete(isHeadRefresh);
                        changeShowIsHaveData(false);
                        hideCricleProgress();
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        long end = System.nanoTime();
//                        CWLog.d(TAG,"失败 时间end2： " + ((end - start) / (1000000)));
                        super.failed(errorCode, data);
                        CWLog.d(TAG, "请求失败 curPage" + curPage + "：" + data);
                        refreshComplete(isHeadRefresh);
                        changeShowIsHaveData(false);
                        hideCricleProgress();
                    }

                    @Override
                    public void success(Object data) {
                        long end = System.nanoTime();
//                        CWLog.d(TAG,"成功 时间end： " + ((end - start) / (1000000)));
                        hideCricleProgress();
                        refreshComplete(true);
                        WorkBookBean workBookBean = (WorkBookBean) data;
                        pageCount = workBookBean.getPageCount();
                        curPage = workBookBean.getPage() + 1;
                        CWLog.d(TAG, "请求成功 curPage" + curPage + "：" + data);
                        ArrayList<PageListBean> pageListNet = (ArrayList<PageListBean>) workBookBean.getPageList();
                        if (isHeadRefresh || isFreshOrLoadmore) {
                            workBookAdapter.setData(pageListNet);
                            changeStateNoChecked();
                        } else {
                            if (null != pageListNet && pageListNet.size() <= 0) {
                                refreshWorkbook.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                                return;
                            }
                            workBookAdapter.addNewData(pageListNet);
                        }
                        pageList = workBookAdapter.getData();

                        if (pageList != null && pageList.size() > 0) {
                            changeShowIsHaveData(true);
                        } else {
                            changeShowIsHaveData(false);
                        }
                    }
                });
    }

    /**
     * 改变未选中单词时与否状态
     */
    private void changeStateNoChecked() {
        checkedWordList.clear();
        setPartTextColor(tvCheckedNum, checkedWordList.size());//刷新改变选中数量
        if (checkedWordList.size() <= 0 && workBookAdapter.getCheckWordIconVisiable()) {
            tvPractice.setBackgroundResource(R.color.color_AAB2AE);
        } else {
            tvPractice.setBackgroundResource(R.color.color_light_green);
        }

    }

    /**
     * 开始练习
     */

    private void startPractice() {
        if (EConstants.IS_YOUKE) {//添加游客模式控制
            NewLoginDialog newLoginDialog = new NewLoginDialog(this);
            newLoginDialog.showLoginDialog();
            return;
        }

        if (checkedWordList.size() <= 0) return;//未选中单词时不让点击
        if (!NetworkUtils.isOnline()) {//检查网络
            ToastUtil.INSTANCE.toastInCenter(WorkBookActivity.this, getResources().getString(R.string.connect_disable5), Toast.LENGTH_LONG);
            return;
        }
        WorkBookJumpManager.jumpToWordPracticeActivity(R.string.go_back, WorkBookActivity.this, checkedWordList, WordListReadActivity.REQUEST_CODE_FROM_WORD_LIST);
    }

    /**
     * 取消按钮
     */
    private void cancle() {
        //recycleview 改变
        workBookAdapter.setCheckWordIconVisiable(false);
        cancleAllSelected();
        //标题栏改变
        textTittle = "刷单词";
        setTitleText(textTittle);
        showBackBar();
        hideRightBtn();

        //提示文字改变
        tvCheckedNum.setVisibility(View.GONE);
        tvPips.setVisibility(View.VISIBLE);
        tvCheckRange.setVisibility(View.VISIBLE);
        ////底部文字按钮改变 开始练习
        tvPractice.setText("去练习");
    }

    /**
     * 去选单词（去练习）
     */

    private void checkWord() {
        if (workBookAdapter.getData().size() <= 0) return;//当没有数据时点击无效
        //recycleview 改变
        workBookAdapter.setCheckWordIconVisiable(true);
        defaultSelect();
        //标题栏改变
        textTittle = "选择单词";
        setTitleText(textTittle);
        hideBackBar();
        setRightBtnEnable(true);
        setRightBtnText("取消", R.color.item_nomal);
        setRightBtnListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                //1.实现去除checkbox,2."开始练习“变为“去练习"3.文字指示改变
                cancle();
            }
        });

        //提示文字改变
        tvCheckedNum.setVisibility(View.VISIBLE);
        setPartTextColor(tvCheckedNum, checkedWordList.size());
        tvPips.setVisibility(View.GONE);
        tvCheckRange.setVisibility(View.GONE);
        ////底部文字按钮改变 开始练习
        tvPractice.setText("开始练习");
        rvWord.smoothScrollToPosition(LOCATIONPOSITION);
    }

    /**
     * 默认选择单词
     */

    private void defaultSelect() {
        int num = THRESHOLD_SELECT;
        if (pageList.size() < THRESHOLD_SELECT) {
            num = pageList.size();
        }
        for (int i = 0; i < num; i++) {
            pageList.get(i).setSelected(true);
            checkedWordList.add(pageList.get(i));
            System.out.println("选中单词：" + i + pageList.get(i).getContent());
        }
    }

    /**
     * 取消全部选择单词
     */

    private void cancleAllSelected() {
        for (int i = 0; i < pageList.size(); i++) {
            pageList.get(i).setSelected(false);
        }
        checkedWordList.clear();
    }

    /**
     * 选择范围查询单词
     */

    private void checkWorldRange() {
        if (isContinuClick()) return;
        if (checkDialogFragment == null)
            checkDialogFragment = new CheckDialogFragment();

        checkDialogFragment.show(getSupportFragmentManager(), " ");
        checkDialogFragment.setCheckScoreListener(new CheckDialogFragment.ICheckScoreListener() {
            @Override
            public void checkScore(int range) {
                String strRange = null;
                switch (range) {
                    case CheckDialogFragment.ALL:
                        strRange = "全部";
                        scoreRange = "0,100";
                        break;
                    case CheckDialogFragment.BELOW_80:
                        strRange = "低于80分";
                        scoreRange = "0,80";
                        break;
                    case CheckDialogFragment.BELOW_60:
                        strRange = "低于60分";
                        scoreRange = "0,60";
                        break;
                    case CheckDialogFragment.OVER_80:
                        strRange = "高于80分";
                        scoreRange = "80,100";
                        break;
                    case CheckDialogFragment.OVER_60:
                        strRange = "高于60分";
                        scoreRange = "60,100";
                        break;
                    default:
                        strRange = "全部";
                        scoreRange = "0,100";
                }
                tvCheckRange.setText(strRange);
                checkDialogFragment.dismiss();
                curPage = default_page;
                getNetWorkBookListByID(scoreRange, curPage, true, false);

            }
        });
    }

    /**
     * 是否连续点击 true 是
     *
     * @return
     */
    private boolean isContinuClick() {
        long intervalTime = 500;
        long current = System.currentTimeMillis();
        if ((current - lastTime) < intervalTime) {
            lastTime = current;
            return true;
        }
        lastTime = current;
        return false;
    }
}
